package com.first.community.service;

import com.first.community.dto.CommentDTO;
import com.first.community.enums.NotificationStatusEnum;
import com.first.community.enums.NotificationTypeEnum;
import com.first.community.enums.commentTypeEnums;
import com.first.community.exception.CustomizeErrorCode;
import com.first.community.exception.CustomizeExcetpion;
import com.first.community.mapper.*;
import com.first.community.model.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CommentService {
    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private QuestionExtMapper questionExtMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private  UserMapper userMapper;

    @Autowired
    private CommentExtMapper commentExtMapper;

    @Autowired
    private  NotificationMapper notificationMapper;

    @Transactional
    public void insert(Comment comment,User commentator) {

        if(comment.getParentId()==null || comment.getParentId()==0){
            throw new CustomizeExcetpion(CustomizeErrorCode.TARGET_NOT_SELECT);
        }
        if(comment.getType()==null || !commentTypeEnums.isEmpty(comment.getType())){
            throw new CustomizeExcetpion(CustomizeErrorCode.TYPE_PARAM_WRONG);
        }
        if(comment.getType()==commentTypeEnums.COMMENT.getType()){
            //回复评论
            Comment dbcomment = commentMapper.selectByPrimaryKey(comment.getParentId());
            if(dbcomment==null){
                throw  new CustomizeExcetpion(CustomizeErrorCode.TARGET_COMMENT_NOT_FOUND) ;
            }
            //检查该评论的问题是否为空
            Question question = questionMapper.selectByPrimaryKey(dbcomment.getParentId());
            if(question==null){
                throw  new CustomizeExcetpion(CustomizeErrorCode.QUESTION_NOT_FOUND);
            }
            commentMapper.insert(comment);

                //增加评论数
                Comment comment1 = new Comment();
                comment1.setId(comment.getParentId());
                comment1.setCommentCount(1L);
                commentExtMapper.incComment(comment1);

                //创建通知
            createNotify(comment,dbcomment.getCommentator(),commentator.getName(),question.getTitle(), NotificationTypeEnum.REPLY_COMMENT,question.getId());
        }else{
            //回复问题
            Question dbquestion = questionMapper.selectByPrimaryKey(comment.getParentId());

            if(dbquestion==null){
                throw  new CustomizeExcetpion(CustomizeErrorCode.QUESTION_NOT_FOUND);
            }
            commentMapper.insert(comment);
            dbquestion.setCommentCount(1);
            questionExtMapper.incComment(dbquestion);

            //创建通知
            createNotify(comment,dbquestion.getCreator(),commentator.getName(),dbquestion.getTitle(),NotificationTypeEnum.REPLY_QUESTION,dbquestion.getId());
        }
    }

    public List<CommentDTO> ListById(Long number,commentTypeEnums commentTypeEnums) {
        CommentExample example = new CommentExample();
        example.createCriteria()
                .andParentIdEqualTo(number)
                .andTypeEqualTo(commentTypeEnums.getType());
        example.setOrderByClause("gmt_create desc");
        List<Comment> comments = commentMapper.selectByExample(example);

        if(comments.size()==0){
            return  new ArrayList<>();
        }
//        获取去重的评论人
        List<Long> commentators = comments.stream().map(comment -> comment.getCommentator()).collect(Collectors.toList());

//        获取评论人转换为map
        UserExample example1 = new UserExample();
        List<User> users = userMapper.selectByExample(example1);
        Map<Long, User> userMap = users.stream().collect(Collectors.toMap(user -> user.getId(), user -> user));

//        转换comment为commentDTO
        List<CommentDTO> commentDTOS = comments.stream().map(comment -> {
            CommentDTO commentDTO = new CommentDTO();
            BeanUtils.copyProperties(comment, commentDTO);
            commentDTO.setUser(userMap.get(comment.getCommentator()));
            return commentDTO;
        }).collect(Collectors.toList());


        return commentDTOS;
    }

    private void createNotify(Comment comment, Long receiver, String notifierName, String outerTitle, NotificationTypeEnum notificationTypeEnum,Long outerId){
        if(receiver == comment.getCommentator()){
            return;
        }
        Notification notification = new Notification();
        notification.setGmtCreate(System.currentTimeMillis());
        notification.setType(notificationTypeEnum.getType());
        notification.setOuterid(outerId);
        notification.setOuterTitle(outerTitle);
        notification.setNotifier(comment.getCommentator());
        notification.setStatus(NotificationStatusEnum.UNREAD.getStatus());
        notification.setReceiver(receiver);
        notification.setNotifierName(notifierName);
        notificationMapper.insert(notification);
    }
}
